package com.quanyan.common.utils;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by Zheng.Ke
 * Date 2017/2/20.
 */
public class SignatureUtils {

    private SignatureUtils() {

    }

    /**
     * 将对象的非空字段，按照参数名ASCII码从小到大排序，拼成如下格式的字符串：appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA
     * @param o
     * @return
     */
    public static String getDictString(Object o) {
        ArrayList<String> list = new ArrayList<String>();
        Class cls = o.getClass();
        Field[] fields = cls.getDeclaredFields();
        if (fields == null || fields.length == 0) {
            fields = cls.getSuperclass().getDeclaredFields();
        }
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                if (!StringUtils.isEmpty(f.get(o))) {
                    list.add(f.getName() + "=" + f.get(o) + "&");
                }
            } catch (IllegalAccessException e) {
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                sb.append(arrayToSort[i].substring(0, arrayToSort[i].length()-1));
            } else {
                sb.append(arrayToSort[i]);
            }
        }
        return sb.toString();
    }

    /**
     * 获取微信签名
     * @param o       参与签名的对象
     * @param apiKey  微信api密钥
     * @return
     */
    public static String getWxSign(Object o, String apiKey) {
        StringBuffer dictStringSb = new StringBuffer(getDictString(o));
        dictStringSb.append("&key=").append(apiKey);
        String sign = EncryptUtils.hashByMD5(dictStringSb.toString()).toUpperCase();
        return sign;
    }


}
